import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import type { AiPersonData } from '@/hooks/useAiPersonData';
import infor_1 from '@/assets/images/infor_1.png';
import infor_2 from '@/assets/images/infor_2.png';
import infor_3 from '@/assets/images/infor_3.png';
import infor_4 from '@/assets/images/infor_4.png';
import infor_5 from '@/assets/images/infor_5.png';
import infor_6 from '@/assets/images/infor_6.png';
import { getDynamicFonts } from '@/utils/fontUtils';


interface ChatAlbumProps {
  aiPersonData: AiPersonData | null | undefined;
  loading?: boolean;
  onClose?: () => void;
}

const ChatAlbum: React.FC<ChatAlbumProps> = ({ aiPersonData, loading = false, onClose }) => {
  const { t, i18n } = useTranslation();

  // 根据当前语言动态获取字体
  const dynamicFonts = getDynamicFonts(i18n);

  // 语言映射函数：在日语环境下将"Japanese"显示为"日本語"
  const getLanguageDisplay = (language: string | undefined): string => {
    if (!language) return '';

    // 在日语环境下，将"Japanese"映射为"日本語"
    if (i18n.language === 'ja' && language.toLowerCase() === 'japanese') {
      return '日本語';
    }

    return language;
  };

  // 描述展开状态
  const [descExpanded, setDescExpanded] = useState(false);
  const descRef = useRef<HTMLDivElement>(null);

  // 轮播相关状态
  const [currentIndex, setCurrentIndex] = useState(0);

  // refs for videos
  const videoRefs = useRef<(HTMLVideoElement | null)[]>([]);

  // 检测是否为移动端
  const isMobile = typeof window !== 'undefined' && window.innerWidth < 1024;

  // 构建轮播项目：第一张图片 + 第一个视频 + 剩余图片
  const carouselItems: { type: 'image' | 'video'; src: string }[] = [];

  // 第一张：images的第一张图片
  if (aiPersonData?.images && aiPersonData.images.length > 0) {
    carouselItems.push({ type: 'image', src: aiPersonData.images[0] });
  }

  // 第二张：第一个视频
  if (aiPersonData?.videos && aiPersonData.videos.length > 0) {
    carouselItems.push({ type: 'video', src: aiPersonData.videos[0] });
  }

  // 第三张开始：剩余的图片
  if (aiPersonData?.images && aiPersonData.images.length > 1) {
    aiPersonData.images.slice(1).forEach(img =>
      carouselItems.push({ type: 'image', src: img })
    );
  }

  const total = carouselItems.length;
  const goTo = (idx: number) => setCurrentIndex((idx + total) % total);
  const goPrev = () => goTo(currentIndex - 1);
  const goNext = () => goTo(currentIndex + 1);

  // 计算需要渲染的资源范围（当前 + 前后各1个）
  const shouldRenderItem = (index: number): boolean => {
    if (total === 0) return false;
    const prevIndex = (currentIndex - 1 + total) % total;
    const nextIndex = (currentIndex + 1) % total;
    return index === currentIndex || index === prevIndex || index === nextIndex;
  };

  // 计算是否应该立即加载（当前项立即加载，相邻项延迟加载）
  const shouldLoadImmediately = (index: number): boolean => {
    return index === currentIndex;
  };

  // 处理视频的动态加载和播放
  useEffect(() => {
    carouselItems.forEach((item, idx) => {
      if (item.type === 'video' && videoRefs.current[idx]) {
        const videoEl = videoRefs.current[idx];
        if (!videoEl) return;

        if (shouldRenderItem(idx)) {
          // 需要渲染的视频，设置src（如果还没有的话）
          if (!videoEl.src && shouldLoadImmediately(idx)) {
            videoEl.src = item.src;
          }

          // 当前视频自动播放，其他暂停
          if (idx === currentIndex) {
            videoEl.play?.().catch(() => {
              // 忽略自动播放失败
            });
          } else {
            videoEl.pause?.();
          }
        }
      }
    });
  }, [currentIndex, carouselItems]);

  // 预加载相邻视频的src
  useEffect(() => {
    const timer = setTimeout(() => {
      carouselItems.forEach((item, idx) => {
        if (item.type === 'video' && shouldRenderItem(idx) && !shouldLoadImmediately(idx)) {
          const videoEl = videoRefs.current[idx];
          if (videoEl && !videoEl.src) {
            videoEl.src = item.src;
          }
        }
      });
    }, 200); // 延迟200ms预加载相邻视频

    return () => clearTimeout(timer);
  }, [currentIndex, carouselItems]);

  // 重置轮播
  useEffect(() => {
    setCurrentIndex(0);
  }, [aiPersonData?.id]);

  // up按钮组件
  const UpButton = ({ onClick }: { onClick: () => void }) => (
    <div
      className="float-end border-2 border-[rgb(231,82,117)] h-6 px-2 rounded-lg text-center transition-all duration-300 hover:bg-white group flex items-center justify-center ml-2"
      style={{ cursor: 'pointer', minWidth: 36, fontFamily: dynamicFonts.font3 }}
      onClick={onClick}
    >
      <span className="text-[rgb(231,82,117)] group-hover:text-[rgb(231,82,117)] transition-all duration-300 text-[0.9rem] h-full flex items-center">
        {t('album.collapseUp')}
      </span>
    </div>
  );

  return (
    <>
      <div className="relative z-10 h-full overflow-y-auto bg-[rgb(23,23,23)] flex flex-col custom-scrollbar-thin"
        style={isMobile ? undefined : { minWidth: '240px', maxWidth: '384px', overflow: 'auto' }}
      >
        <div className="flex flex-col items-center pb-8">
          {loading ? (
            <div className="flex justify-center items-center h-[40vh]">
              <div className="animate-pulse flex flex-col items-center">
                <div className="w-12 h-12 border-4 border-t-pink-500 border-r-transparent border-b-pink-500 border-l-transparent rounded-full animate-spin"></div>
                <p className="mt-4 text-white opacity-80">{t('album.loadingImages')}</p>
              </div>
            </div>
          ) : total > 0 ? (
            <>
              {/* 轮播区域 */}
              <div className={`relative w-full flex items-center justify-center mb-4 ${isMobile ? 'aspect-[9/13]' : 'max-w-sm aspect-[9/16]'
                }`}>
                {/* 移动端Back按钮 - 悬浮在轮播图左上角 */}
                {isMobile && onClose && (
                  <button
                    onClick={onClose}
                    className="absolute top-3 left-3 z-20  h-10 py-2 px-1 flex items-center justify-center rounded-2xl transition-all duration-200 hover:scale-105"
                    style={{
                      backgroundColor: 'rgba(0, 0, 0, 0.3)',
                      backdropFilter: 'blur(10px)',
                      WebkitBackdropFilter: 'blur(10px)',
                      border: '1px solid rgba(255, 255, 255, 0.1)',
                    }}
                    aria-label="Back"
                  >
                    <i className="fas fa-arrow-left text-white text-sm"></i>
                    <span style={{ fontFamily: dynamicFonts.font4 }} className='ml-2'>{t('album.back')}</span>
                  </button>
                )}

                {carouselItems.map((item, idx) => {
                  // 只渲染需要的资源（当前 + 相邻）
                  if (!shouldRenderItem(idx)) {
                    return null;
                  }

                  const isCurrentItem = idx === currentIndex;
                  const shouldLoadNow = shouldLoadImmediately(idx);

                  return item.type === 'image' ? (
                    <img
                      key={idx}
                      src={item.src}
                      alt="carousel"
                      className={`w-full h-full shadow-lg cursor-pointer absolute top-0 left-0 bg-black ${isMobile ? 'object-cover' : 'object-contain'
                        }`}
                      loading={shouldLoadNow ? "eager" : "lazy"}
                      style={{
                        opacity: isCurrentItem ? 1 : 0,
                        pointerEvents: isCurrentItem ? 'auto' : 'none',
                        zIndex: isCurrentItem ? 10 : 0,
                        transition: 'none',
                        display: 'block',
                      }}
                    />
                  ) : (
                    <video
                      key={idx}
                      ref={el => videoRefs.current[idx] = el}
                      src={shouldLoadNow ? item.src : undefined}
                      autoPlay={isCurrentItem}
                      muted
                      loop
                      playsInline
                      className={`w-full h-full shadow-lg bg-black absolute top-0 left-0 ${isMobile ? 'object-cover' : 'object-contain'
                        }`}
                      preload={shouldLoadNow ? "auto" : "none"}
                      controls={false}
                      style={{
                        opacity: isCurrentItem ? 1 : 0,
                        pointerEvents: isCurrentItem ? 'auto' : 'none',
                        zIndex: isCurrentItem ? 10 : 0,
                        transition: 'none',
                        display: 'block',
                      }}
                    />
                  );
                })}

                {/* 左箭头 */}
                {total > 1 && (
                  <button
                    className="absolute border-stone-300 hover:border-[white] left-6 top-1/2 -translate-y-1/2 bg-[rgb(143,136,130)] bg-opacity-60 text-white rounded-full z-10 w-11 h-11 flex items-center justify-center focus:outline-none active:outline-none"
                    onClick={goPrev}
                    aria-label="Previous"
                  >
                    <i className="fas fa-chevron-left text-[1.2rem]"></i>
                  </button>
                )}

                {/* 右箭头 */}
                {total > 1 && (
                  <button
                    className="absolute border-stone-300 hover:border-[white] right-6 top-1/2 -translate-y-1/2 bg-[rgb(143,136,130)] bg-opacity-60 text-white rounded-full z-10 w-11 h-11 flex items-center justify-center focus:outline-none active:outline-none"
                    onClick={goNext}
                    aria-label="Next"
                  >
                    <i className="fas fa-chevron-right text-[1.2rem]"></i>
                  </button>
                )}

                {/* 指示器 */}
                {total > 1 && (
                  <div className="absolute bottom-2 left-1/2 -translate-x-1/2 flex gap-2 z-10">
                    {carouselItems.map((_, idx) => (
                      <span
                        key={idx}
                        className={`w-2 h-2 rounded-full ${idx === currentIndex ? 'bg-pink-500' : 'bg-gray-400'} transition-all cursor-pointer`}
                        onClick={() => goTo(idx)}
                      />
                    ))}
                  </div>
                )}
              </div>

              {/* 信息区域 */}
              <div className="w-full max-w-sm px-6 mb-2">
                {/* 名字和收起按钮 */}
                <div className="flex justify-between items-center">
                  <p className='text-[1.5rem] font-bold text-white mb-1' style={{ fontFamily: dynamicFonts.font3 }}>
                    {aiPersonData?.information?.name || aiPersonData?.username}
                  </p>
                  {descExpanded && <UpButton onClick={() => setDescExpanded(false)} />}
                </div>

                {/* 简介 */}
                {aiPersonData?.description && (
                  <>
                    <div
                      ref={descRef}
                      style={{ fontFamily: dynamicFonts.font2 }}
                      className={`text-[rgb(212,212,216)] text-[0.9rem] relative transition-all duration-200 ${descExpanded ? '' : 'line-clamp-3 overflow-hidden'}`}
                    >
                      {aiPersonData.description}
                    </div>

                    {/* 简介的展开和收起按钮 */}
                    <div className="text-right mb-2 flex justify-end" style={{ fontFamily: dynamicFonts.font2 }}>
                      {descExpanded && <UpButton onClick={() => setDescExpanded(false)} />}
                      {!descExpanded && (
                        <span
                          className="text-[rgb(231,82,117)] cursor-pointer select-none"
                          onClick={() => setDescExpanded(true)}
                          style={{ userSelect: 'none' }}
                        >
                          <div
                            className='float-end border-2 border-[rgb(231,82,117)] px-2 mt-2 rounded-md text-center transition-all duration-300 hover:bg-white group flex items-center justify-center'
                            style={{ cursor: 'pointer', minWidth: 36, fontFamily: dynamicFonts.font3 }}
                          >
                            <span className="text-[rgb(231,82,117)] transition-all duration-300 text-[0.9rem]">{t('album.expandMore')}</span>
                          </div>
                        </span>
                      )}
                    </div>
                  </>
                )}
              </div>

              <div className="w-full max-w-sm border-b-2 border-[rgb(69,69,69)] my-2"></div>

              {/* 详细信息列表 */}
              <div className="w-[85%] m-auto max-w-sm text-left text-gray-300 text-sm" style={{ fontFamily: dynamicFonts.font2 }}>
                {/* 标题 */}
                <div style={{ fontFamily: dynamicFonts.font4 }} className='text-[rgb(161,161,161)] text-[0.9rem] mb-8 mt-6 flex items-center'>
                  {t('album.aboutMe')}
                </div>

                <div className="grid grid-cols-2 gap-x-4 gap-y-8">
                  {/* 年龄 */}
                  {(aiPersonData?.information?.age || aiPersonData?.age) && (
                    <div className="flex items-start">
                      <span className="flex-shrink-0 w-9 h-9 flex items-center justify-center rounded-full border border-gray-500 mr-2 overflow-hidden">
                        <img src={infor_1} alt="age" className="w-[1.2rem] h-[1.2rem] object-contain" />
                      </span>
                      <div className="flex flex-col">
                        <span className="font-semibold text-[0.7rem] text-gray-400">{t('album.age')}</span>
                        <span className="text-sm text-white">{aiPersonData?.information?.age || aiPersonData?.age}</span>
                      </div>
                    </div>
                  )}

                  {/* 性别 */}
                  {(aiPersonData?.information?.gender || aiPersonData?.gender) && (
                    <div className="flex items-start">
                      <span className="flex-shrink-0 w-9 h-9 flex items-center justify-center rounded-full border border-gray-500 mr-2 overflow-hidden">
                        <img src={infor_2} alt="gender" className="w-[1.2rem] h-[1.2rem] object-contain" />
                      </span>
                      <div className="flex flex-col">
                        <span className="font-semibold text-[0.7rem] text-gray-400">{t('album.gender')}</span>
                        <span className="text-sm text-white">{aiPersonData?.information?.gender || aiPersonData?.gender}</span>
                      </div>
                    </div>
                  )}

                  {/* 星座 */}
                  {(aiPersonData?.information?.zodiac || aiPersonData?.zodiac) && (
                    <div className="flex items-start">
                      <span className="flex-shrink-0 w-9 h-9 flex items-center justify-center rounded-full border border-gray-500 mr-2 overflow-hidden">
                        <img src={infor_3} alt="zodiac" className="w-[1.2rem] h-[1.2rem] object-contain" />
                      </span>
                      <div className="flex flex-col">
                        <span className="font-semibold text-[0.7rem] text-gray-400">{t('album.zodiac')}</span>
                        <span className="text-sm text-white">{aiPersonData?.information?.zodiac || aiPersonData?.zodiac}</span>
                      </div>
                    </div>
                  )}

                  {/* 生日 */}
                  {(aiPersonData?.information?.birthday || aiPersonData?.birthday) && (
                    <div className="flex items-start">
                      <span className="flex-shrink-0 w-9 h-9 flex items-center justify-center rounded-full border border-gray-500 mr-2 overflow-hidden">
                        <img src={infor_5} alt="language" className="w-[1.2rem] h-[1.2rem] object-contain" />

                      </span>
                      <div className="flex flex-col">
                        <span className="font-semibold text-[0.7rem] text-gray-400">{t('album.birthday')}</span>
                        <span className="text-sm text-white">{aiPersonData?.information?.birthday || aiPersonData?.birthday}</span>
                      </div>
                    </div>
                  )}

                  {/* 语言 */}
                  {(aiPersonData?.information?.language || aiPersonData?.language) && (
                    <div className="flex items-start">
                      <span className="flex-shrink-0 w-9 h-9 flex items-center justify-center rounded-full border border-gray-500 mr-2 overflow-hidden">
                        <img src={infor_4} alt="birthday" className="w-[1.1rem] h-[1.1rem] object-contain" />

                      </span>
                      <div className="flex flex-col">
                        <span className="font-semibold text-[0.7rem] text-gray-400">{t('album.language')}</span>
                        <span className="text-sm text-white">{getLanguageDisplay(aiPersonData?.information?.language || aiPersonData?.language)}</span>
                      </div>
                    </div>
                  )}

                  {/* 职业 */}
                  {(aiPersonData?.information?.occupation || aiPersonData?.occupation || (aiPersonData?.jobs && aiPersonData.jobs.length > 0)) && (
                    <div className="flex items-start">
                      <span className="flex-shrink-0 w-9 h-9 flex items-center justify-center rounded-full border border-gray-500 mr-2 overflow-hidden">
                        <img src={infor_6} alt="occupation" className="w-[1.2rem] h-[1.2rem] object-contain" />
                      </span>
                      <div className="flex flex-col">
                        <span className="font-semibold text-[0.7rem] text-gray-400">{t('album.occupation')}</span>
                        <span className="text-sm text-white">{aiPersonData?.information?.occupation || aiPersonData?.occupation || aiPersonData?.jobs?.[0]}</span>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </>
          ) : (
            <div className="flex justify-center items-center h-[40vh]">
              <div className="text-center">
                <i className="fas fa-image text-4xl text-gray-500 mb-4"></i>
                <p className="text-gray-400">{t('album.noImages')}</p>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

export default ChatAlbum; 